package org.tagging.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class ResponseUtils {
    /**
     * JSONObject.toJSONString使用了反射，因此若想json化需要有对应的getter方法
     * @param status
     * @param message
     * @param data
     * @return
     *  "authorities": {
     *         "$ref": "$.data[0].authorities"
     *       },
     *       出现以上原因是因为使用fastjson的jsonarray类型作为返回数据时，当向jsonArray对象添加jsonObject对象，
     *       而jsonObject队形包含相同的节点数据时，fastjson会防止数据栈溢出自动将想用的节点数据采用引用方式替代；
     *       进制循环引用即可         return JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
     */
    public static String build(int status, String message, Object data) {
        Map<String, Object> map = new HashMap<>();
        map.put("timestamp", System.currentTimeMillis());
        map.put("code", status);
        map.put("message", message);
        map.put("data", data);
        return JSONObject.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
    }

    public static String build(int status, String message) {
        return build(status, message, null);
    }

    public static void printJson(HttpServletResponse response, String data) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.println(data);
        printWriter.close();
    }

    public static String buildJSONString(Object build) {
        return JSONObject.toJSONString(build);
    }
}
